﻿<template>
    <el-dialog
        title="补充材料"
        v-model="visible"
        :width="1000"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="物料编码" prop="materialCode">
                        <el-input v-model="entityObj.materialCode" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="物料名称" prop="materialName">
                        <el-input v-model="entityObj.materialName" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="物料分类" prop="materialTypeId">
                        <el-tree-select
                            placeholder="---请选择物料分类---"
                            collapse-tags
                            collapse-tags-tooltip
                            v-model="entityObj.materialTypeId"
                            :props="{ label: 'label', value:'value',children: 'children' }"
                            :default-expand-all="true"
                            :data="materialTypeTree"
                            filterable
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="物料规格" prop="materialSpecs">
                        <el-input v-model="entityObj.materialSpecs" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="品牌" prop="brandCodes">
                        <el-select
                            placeholder="---请选择品牌---"
                            v-model="entityObj.brandCodes"
                            multiple
                            style="width: 100%"
                        >
                            <el-option
                                v-for="item in optionsBrand"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="物料材质">
                        <el-input v-model="entityObj.materialQuality" />
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="物料单位">
                        <el-button size="small" @click="addUnit()">增加单位</el-button>
                    </el-form-item>
                </el-col>
            </el-row>-->
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="物料单位" prop="materialItems">
                        <el-table :data="entityObj.materialItems" border style="width: 100%">
                            <el-table-column label="单位名称" prop="unitCode" min-width="160px">
                                <template #default="scope">
                                    <el-form-item>
                                        <el-select
                                            placeholder="---请选择单位---"
                                            v-model="scope.row.unitCode"
                                            style="width: 300px"
                                            :disabled="entityObj.purchaseProtocols.some(p=>p.unitCode==scope.row.unitCode)||entityObj.deliveryProtocols.some(p=>p.unitCode==scope.row.unitCode)"
                                            @change="val=>unitHandleChange(val,scope.row)"
                                        >
                                            <el-option
                                                v-for="item in optionsUnit"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="是否一次性物料" min-width="160" prop="isDisposable">
                                <template #default="scope">
                                    <el-switch
                                        v-model="scope.row.isDisposable"
                                        :active-value="true"
                                        :inactive-value="false"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="是否最小单位" min-width="160" prop="isMinUnit">
                                <template #default="scope">
                                    <el-switch
                                        v-model="scope.row.isMinUnit"
                                        :active-value="true"
                                        :inactive-value="false"
                                        @change="setIsMinUnit(scope.$index)"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="换算系数" min-width="180" prop="unitQty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.unitQty"
                                        style="width: 100%"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="供店价" min-width="180" prop="applyPrice">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.applyPrice"
                                        style="width: 100%"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="操作" width="100">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        @click="deleteRow (scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>-->
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="供店价">
                        <el-button size="small" @click="addDeliveryProtocol()">增加供店价</el-button>
                    </el-form-item>
                </el-col>
            </el-row>-->
            <!-- <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="供店价" prop="deliveryProtocols">
                        <el-table :data="entityObj.deliveryProtocols" border style="width: 100%">
                            <el-table-column label="单位名称" prop="unitCode" min-width="160px">
                                <template #default="scope">
                                    <el-form-item>
                                        <el-select
                                            placeholder="---请选择单位---"
                                            v-model="scope.row.unitCode"
                                            style="width: 300px"
                                        >
                                            <el-option
                                                v-for="item in entityObj.materialItems"
                                                :key="item.unitCode"
                                                :label="item.unitName"
                                                :value="item.unitCode"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="供店价" min-width="180" prop="unitQty">
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.price" style="width: 100%"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" min-width="100">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        @click="delDeliveryProtocol (scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>-->
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="进货价" prop="purchaseProtocols">
                        <el-button size="small" @click="addPurchaseProtocol()">增加进货价</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label >
                        <el-table :data="entityObj.purchaseProtocols" border style="width: 100%">
                            <el-table-column label="单位名称" prop="unitCode" min-width="160px">
                                <template #default="scope">
                                    <el-form-item>
                                        <el-select
                                            placeholder="---请选择单位---"
                                            v-model="scope.row.unitCode"
                                            style="width: 300px"
                                        >
                                            <el-option
                                                v-for="item in entityObj.materialItems"
                                                :key="item.unitCode"
                                                :label="item.unitName"
                                                :value="item.unitCode"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="供应商" prop="supplierId" min-width="180px">
                                <template #default="scope">
                                    <el-form-item>
                                        <el-select
                                            placeholder="---请选择供应商---"
                                            v-model="scope.row.supplierId"
                                            filterable
                                            style="width: 300px"
                                        >
                                            <el-option
                                                v-for="item in suppliers"
                                                :key="item.supplierId"
                                                :label="item.supplierName"
                                                :value="item.supplierId"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="进货价" min-width="180" prop="unitQty">
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.price" style="width: 100%"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" min-width="100">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        @click="delPurchaseProtocol (scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="物料缩略图" prop="materialImage">
                        <sc-upload
                            v-model="entityObj.materialThumbnailImage"
                            :objName="'Supply/Material'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                            tip="最多上传1个文件,请上传图像格式文件"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="物料图片" prop="materialImage">
                        <sc-upload-multiple
                            v-model="entityObj.materialImage"
                            :objName="'Supply/Material'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="8"
                            tip="最多上传8个文件,请上传图像格式文件"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button
                v-if="mode != 'Show'"
                type="primary"
                :loading="isSaveing"
                @click="submit()"
            >保 存</el-button>
        </template>
    </el-dialog>
</template>

<script>
import tool from "@/utils/tool";
import { forEach } from "jszip";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                minStock: 0,
                minDeliveryQty: 1,
                isSpecial: false,
                status: 1,
                generalRate: 0,
                incrementRate: 0,
                materialItems: [
                    {
                        unitCode: "",
                        unitName: "",
                        isMinUnit: true,
                        isDisposable:false,
                        unitQty: 1,
                        applyPrice: 0,
                    },
                ],
                deliveryProtocols: [],
                purchaseProtocols: [],
            },
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                // materialCode: [
                //     {
                //         required: true,
                //         type: "string",
                //         message: "请填写物料编码",
                //     },
                // ],
                materialName: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写物料名称",
                    },
                ],
                materialTypeId: [
                    {
                        required: true,
                        type: "number",
                        message: "请填写物料分类",
                    },
                ],
                materialSpecs: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写物料规格",
                    },
                ],
                brandCodes: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写物料品牌",
                        trigger: "change",
                    },
                ],
                // generalRate: [
                //     {
                //         required: true,
                //         type: "number",
                //         message: "请填写普票税率",
                //         trigger: "change",
                //     },
                // ],
                // incrementRate: [
                //     {
                //         required: true,
                //         type: "number",
                //         message: "请填写增票税率",
                //         trigger: "change",
                //     },
                // ],
                materialItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写物料单位",
                        trigger: "change",
                    },
                ],
                deliveryProtocols: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写供店价",
                        trigger: "change",
                    },
                ],
                purchaseProtocols: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写进货价",
                        trigger: "change",
                    },
                ],
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            suppliers: [],
        };
    },
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //添加单位
        addUnit() {
            this.entityObj.materialItems = [
                ...this.entityObj.materialItems,
                {},
            ];
        },
        //删除单位
        deleteRow(index) {
            const unitCode = this.entityObj.materialItems[index].unitCode;
            if (
                this.entityObj.deliveryProtocols.some(
                    (p) => p.unitCode == unitCode
                ) ||
                this.entityObj.purchaseProtocols.some(
                    (p) => p.unitCode == unitCode
                )
            ) {
                this.$message.error("请先删除价格中该物料单位");
                return;
            }
            this.entityObj.materialItems.splice(index, 1);
        },
        //修改单位
        unitHandleChange(val, row) {
            row.unitName = this.optionsUnit.find(
                (option) => option.value === row.unitCode 
            )?.label;
        },
        //过滤已选中的选项
        availableOptions(currentRow) {
            // 获取已选单位
            const selectedValues = this.entityObj.materialItems
                .filter((row) => row.unitCode) // 过滤出已选择的单位
                .map((row) => row.unitCode); // 获取已选择的单位代码

            // 返回未被选择的单位选项
            return this.optionsUnit.filter(
                (item) =>
                    !selectedValues.includes(item.value) ||
                    item.value == currentRow.unitCode
            );
        },
        //添加配送协议
        addDeliveryProtocol() {
            if (
                !this.entityObj.materialItems ||
                this.entityObj.materialItems.length == 0
            ) {
                this.$message.error("请先添加物料单位");
                return;
            }
            if (this.entityObj.materialItems.some((p) => !p.unitCode)) {
                this.$message.error("物料单位不能为空");
                return;
            }

            this.entityObj.deliveryProtocols.push({
                storeId: this.entityObj.storeId,
                unitCode: this.entityObj.materialItems[0].unitCode,
                price: 0,
                isDisposable:p.isDisposable
            });
        },
        //过滤已选中的选项
        // deliveryProtocolOptions(currentRow) {
        //     // 获取已选单位
        //     const selectedValues = this.entityObj.deliveryProtocols
        //         .filter((row) => row.unitCode) // 过滤出已选择的单位
        //         .map((row) => row.unitCode); // 获取已选择的单位代码

        //     // 返回未被选择的单位选项
        //     return this.entityObj.materialItems.filter(
        //         (item) => !selectedValues.includes(item.unitCode)||item.unitCode==currentRow.unitCode
        //     );
        // },
        //删除配送协议
        delDeliveryProtocol(index) {
            this.entityObj.deliveryProtocols.splice(index, 1);
        },
        //添加采购协议
        addPurchaseProtocol() {
            if (
                !this.entityObj.materialItems ||
                this.entityObj.materialItems.length == 0
            ) {
                this.$message.error("请先添加物料单位");
                return;
            }

            if (this.entityObj.materialItems.some((p) => !p.unitCode)) {
                this.$message.error("物料单位不能为空");
                return;
            }

            if (!this.suppliers || this.suppliers.length == 0) {
                this.$message.error("请先在采购单位管理中绑定对应供应商");
                return;
            }

            this.entityObj.purchaseProtocols.push({
                supplier: this.suppliers[0],
                unitCode: this.entityObj.materialItems[0].unitCode,
                price: 0,
                isDisposable:1
            });
        },
        //过滤已选中的选项
        // purchaseProtocolOptions(currentRow) {
        //     // 获取已选单位
        //     const selectedValues = this.entityObj.purchaseProtocols
        //         .filter((row) => row.unitCode) // 过滤出已选择的单位
        //         .map((row) => row.unitCode); // 获取已选择的单位代码

        //     // 返回未被选择的单位选项
        //     return this.entityObj.materialItems.filter(
        //         (item) => !selectedValues.includes(item.unitCode)||item.unitCode==currentRow.unitCode
        //     );
        // },
        //删除采购协议
        delPurchaseProtocol(index) {
            this.entityObj.purchaseProtocols.splice(index, 1);
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    if (
                        !this.entityObj.materialItems ||
                        this.entityObj.materialItems.length == 0
                    ) {
                        this.$message.error("物料单位不能为空");
                        return;
                    }

                    console.log('materialItems',this.entityObj.materialItems)
                    this.entityObj.materialItems.map((p) => {
                        this.entityObj.deliveryProtocols.push({
                            storeId: this.entityObj.storeId,
                            unitCode: p.unitCode,
                            price: p.applyPrice,
                            isDisposable:p.isDisposable
                        });
                    }); 

                    console.log('deliveryProtocols',this.entityObj.deliveryProtocols)

                    this.entityObj.isSpecial = false;
                    this.entityObj.generalRate = 0;
                    this.entityObj.incrementRate = 0;
                    this.entityObj.status = 1;
                    this.entityObj.minStock = 0;
                    this.entityObj.minDeliveryQty = 1;
                    this.entityObj.purchaseUnitCode =
                        this.entityObj.materialItems.find(
                            (p) => p.isMinUnit
                        )?.unitCode;
                    this.entityObj.purchaseUnitName =
                        this.entityObj.materialItems.find(
                            (p) => p.isMinUnit
                        )?.unitName;
                    this.entityObj.saleUnitCode =
                        this.entityObj.materialItems.find(
                            (p) => p.isMinUnit
                        )?.unitCode;
                    this.entityObj.saleUnitName =
                        this.entityObj.materialItems.find(
                            (p) => p.isMinUnit
                        )?.unitName;
                    this.entityObj.stockUnitCode =
                        this.entityObj.materialItems.find(
                            (p) => p.isMinUnit
                        )?.unitCode;
                    this.entityObj.stockUnitName =
                        this.entityObj.materialItems.find(
                            (p) => p.isMinUnit
                        )?.unitName;
                    this.entityObj.auxiliaryUnitCode =
                        this.entityObj.materialItems.find(
                            (p) => p.isMinUnit
                        )?.unitCode;
                    this.entityObj.auxiliaryUnitName =
                        this.entityObj.materialItems.find(
                            (p) => p.isMinUnit
                        )?.unitName;
                    this.isSaveing = true;
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "material/create", 
                                { ...this.entityObj }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            var materialValue = await this.$API.auth.PostProcessApi.post("delivery-protocol/material-item-pages", { materialItemIds:[returnValue.response],isAll:true });
                            if(materialValue.status==200){
                                console.log(materialValue.response)
                                this.$emit("setTempMaterial",materialValue.response.data);
                                this.isSaveing = false;
                                this.visible = false;
                            }
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //设置最小单位
        async setIsMinUnit(index) {
            this.entityObj.materialItems.map((p, i) => {
                p.isMinUnit = false;
                if (index == i) p.isMinUnit = true;
            });
        },
        //设置要货单位
        async setIsApplyUnit(index) {
            this.entityObj.materialItems.map((p, i) => {
                p.isApplyUnit = false;
                if (index == i) p.isApplyUnit = true;
            });
        },
        getMaterialTypeId(tree,name){
            tree.forEach(item=>{
                if(item.label==name){
                    return item.value;
                }

                if (item.children && item.children.length > 0) {
                    const value = this.getMaterialTypeId(item.children, name);
                    if (value) {
                        return value; // 返回找到的节点
                    }
                }
            });
            return null;
        },
        //表单注入数据
        async setData(data) {
            this.entityObj.storeId = data.storeId;
            this.entityObj.materialName = data.materialName;
            this.entityObj.materialSpecs = data.materialSpecs;
            this.entityObj.remarks = "";
            const unit = this.optionsUnit.find((p) => p.unitName=data.unitName);
            if (unit) {
                his.entityObj.materialItems[0].unitCode = unit.unitCode;
            }
            this.entityObj.materialTypeId=this.getMaterialTypeId(this.materialTypeTree,data.materialTypeName)
            try {
                var returnValue = await this.$API.auth.GetProcessApi.get(
                    `/purchase-unity-supplier-relation/${this.entityObj.orgId}`, 
                    {}
                );
                if (returnValue.status == 200) {
                    this.suppliers = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/dic-options",
                    { ParentBaseDictionaryCodes: ["001", "002"] }
                );
                if (returnValue.status == 200) {
                    this.optionsBrand = returnValue.response.find(
                        (p) => p.code == "001"
                    ).optionsDetails;
                    this.optionsUnit = returnValue.response.find(
                        (p) => p.code == "002"
                    ).optionsDetails;

                    if (this.optionsUnit && this.optionsUnit.length > 0) {
                        this.entityObj.purchaseUnitCode =
                            this.optionsUnit[0].value;
                        this.entityObj.saleUnitCode = this.optionsUnit[0].value;
                        this.entityObj.stockUnitCode =
                            this.optionsUnit[0].value;
                        this.entityObj.auxiliaryUnitCode =
                            this.optionsUnit[0].value;
                    }
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
    },
    async mounted() {
        this.entityObj.orgName = tool.data.get("USER_INFO").OrgName;
        this.entityObj.orgId = tool.data.get("USER_INFO").OrgId;
        await this.initOptions();
    },
};
</script>

<style></style>
